<template>
	<el-container>
		<el-header class="header-tabs">
			<el-tabs type="card" v-model="search.status" @tab-change="tabChange">
				<el-tab-pane label="全部" name=""></el-tab-pane>
				<el-tab-pane label="未支付" name="0"></el-tab-pane>
				<el-tab-pane label="已支付" name="1"></el-tab-pane>
				<el-tab-pane label="收件中" name="2"></el-tab-pane>
				<el-tab-pane label="待补差价" name="3"></el-tab-pane>
				<el-tab-pane label="运输中" name="4"></el-tab-pane>
				<el-tab-pane label="配送完成" name="5"></el-tab-pane>
				<el-tab-pane label="系统取消" name="6"></el-tab-pane>
				<el-tab-pane label="用户主动取消" name="7"></el-tab-pane>
				<el-tab-pane label="取消中" name="8"></el-tab-pane>
				<el-tab-pane label="订单关闭" name="9"></el-tab-pane>
				<el-tab-pane label="拒收退回" name="10"></el-tab-pane>
				<el-tab-pane label="异常" name="11"></el-tab-pane>
				<el-tab-pane label="取消异常" name="12"></el-tab-pane>
				<el-tab-pane label="运输异常" name="13"></el-tab-pane>
			</el-tabs>
		</el-header>
		<el-header>
			<div class="left-panel">
				<!-- <el-button type="primary" icon="el-icon-plus" @click="add"></el-button> -->
				<el-button type="primary" icon="sc-icon-download" @click="onBatchExport">导出</el-button>
				<div class="right-panel-search" style="margin-left: 10px;">
					<el-date-picker style="width: 150px;" v-model="search.start_time" value-format="X" type="date"
						placeholder="开始时间" />
					<el-date-picker style="width: 150px;" v-model="search.end_time" value-format="X" type="date"
						placeholder="截止时间" />
					<el-select style="width: 100px;" v-if="codes.length" v-model="search.code" clearable
						placeholder="快递公司" filterable>
						<el-option v-for="(item, key) in codes" :key="key" :label="item.company_name" :value="item.code" />
					</el-select>
					<el-select style="width: 100px;" v-if="codes.length" v-model="search.service_provider" clearable
						placeholder="服务商" filterable>
						<el-option v-for="(item, key) in service_providers" :key="key" :label="item.label" :value="item.service_provider" />
					</el-select>
					<el-input style="width: 220px;" v-model="search.waybill" placeholder="快递单号" clearable></el-input>
					<el-input style="width: 230px;" v-model="search.ordernum" placeholder="订单号" clearable></el-input>
					<el-input style="width: 100px;" v-model="search.member_id" placeholder="会员ID" clearable></el-input>
					<el-input style="width: 200px;" v-model="search.keyword" placeholder="关键词搜索" clearable></el-input>
					<el-button type="primary" icon="el-icon-search" @click="upsearch"></el-button>
				</div>
			</div>
			<div class="right-panel">
			</div>
		</el-header>
		<el-main class="nopadding">
			<scTable2 ref="table" :apiObj="list.apiObj" :summaryObj="summaryObj" row-key="id" stripe>
				<el-table-column label="ID" prop="id" width="50"></el-table-column>
				<el-table-column label="下单人" prop="member_id" width="150">
					<template #default="scope">
						<p>会员ID：{{scope.row.member_id}}</p>
						<p>手机号：{{scope.row.phone}}</p>
					</template>
				</el-table-column>
				<el-table-column label="快递信息" prop="company_name" width="150">
					<template #default="scope">
						<p>服务商：{{scope.row.service_provider}}</p>
						<p>快递公司：{{scope.row.company_name}}</p>
						<p>邮寄物品：{{scope.row.cargo}}</p>
						<p>运单号：{{scope.row.waybill}}</p>
					</template>
				</el-table-column>
				<el-table-column label="价格" prop="title" width="150">
					<template #default="scope">
						<p v-if="scope.row.valins_pay && parseFloat(scope.row.valins_pay) > 0">保价金额：{{scope.row.valins_pay}}元</p>
						<p>折后预估总价：{{scope.row.price}}元</p>
						<p>保价金额：{{scope.row.valins_pay}}元</p>
						<p>保价费：{{scope.row.valins_fee}}元</p>
						<p>实际折后总价：{{scope.row.total_price}}元</p>
						<p>已付款金额：{{scope.row.amount}}元</p>
						<p>成本：{{scope.row.cost}}元</p>
						<p>利润：{{scope.row.profit}}元</p>
						<p v-if="scope.row.supplement && parseFloat(scope.row.supplement) > 0">需补差价：{{scope.row.supplement}}元</p>
						<p v-if="scope.row.refund_amount && parseFloat(scope.row.refund_amount) > 0">退款金额：{{scope.row.refund_amount}}元</p>
					</template>
				</el-table-column>
				<el-table-column label="优惠" prop="title" width="150">
					<template #default="scope">
						<p>优惠金额：{{scope.row.discount_price}}元</p>
						<!-- <p>电话：{{scope.row.rec_phone}}</p>
						<p>地址：{{scope.row.rec_addr}}</p> -->
					</template>
				</el-table-column>
				<el-table-column label="重量信息" prop="title" width="150">
					<template #default="scope">
						<p>预估：{{scope.row.weight}}公斤</p>
						<p>实际：{{scope.row.last_weight}}公斤</p>
					</template>
				</el-table-column>
				<el-table-column label="寄件人" prop="title" width="150">
					<template #default="scope">
						<p>姓名：{{scope.row.sender_name}}</p>
						<p>电话：{{scope.row.sender_phone}}</p>
						<p>地址：{{scope.row.sender_addr}}</p>
					</template>
				</el-table-column>
				<el-table-column label="收件人" prop="title" width="150">
					<template #default="scope">
						<p>姓名：{{scope.row.rec_name}}</p>
						<p>电话：{{scope.row.rec_phone}}</p>
						<p>地址：{{scope.row.rec_addr}}</p>
					</template>
				</el-table-column>
				<el-table-column label="订单号" prop="ordernum" width="150"></el-table-column>
				<el-table-column label="时间" prop="title" width="150">
                					<template #default="scope">
                						<p>下单时间：{{scope.row.create_time}}</p>
                						<p>预约取件起始时间：{{scope.row.pickup_start_time}}</p>
                						<p>预约取件截止时间：{{scope.row.pickup_end_time}}</p>
                					</template>
              </el-table-column>
              <el-table-column label="快递员" prop="title" width="150">
                              					<template #default="scope">
                              						<p>快递员：{{scope.row.courier_name}}</p>
                              						<p>电话：{{scope.row.courier_mobile}}</p>
                              						<p>取件码：{{scope.row.courier_code}}</p>
												</template>
              </el-table-column>
				<el-table-column label="备注" prop="remark" width="150"></el-table-column>
				<el-table-column label="状态" prop="status" width="150">
					<template #default="scope">
						<p>{{statuss[scope.row.status]}}</p>
					</template>
				</el-table-column>
				<el-table-column label="操作" fixed="right" align="right" width="100">
					<template #default="scope">
							<el-button size="small" v-if="[0,1, 2].includes(scope.row.status)" type="primary"
								@click="table_expressCancel(scope.row)">取消订单</el-button>
							<el-button size="small" v-if="[6].includes(scope.row.status)" type="primary"
								@click="table_expressCancel(scope.row, 1)">退款</el-button>
							<el-button size="small" v-if="[3].includes(scope.row.status)" type="primary"
								@click="table_expressRemind(scope.row)">提醒补差价</el-button>
							<el-button size="small" type="primary"
								@click="table_expressUpdate(scope.row)">编辑</el-button>
							<el-popconfirm title="确定删除吗？" v-if="[7].includes(scope.row.status)" @confirm="table_del(scope.row, scope.$index)">
								<template #reference>
									<el-button text type="primary" size="small">删除</el-button>
								</template>
							</el-popconfirm>
							<el-button size="small" type="info" @click="table_trace(scope.row)">物流轨迹</el-button>
							<el-button size="small" v-if="[0,3].includes(scope.row.status)" type="primary"
								@click="table_pay(scope.row)">去支付</el-button>
					</template>
				</el-table-column>
			</scTable2>
		</el-main>
	</el-container>
	<expressCancel v-if="dialog.expressCancel" ref="expressCancelDialog" @success="handleSaveSuccess" @closed="dialog.expressCancel=false"></expressCancel>
	<expressRemind v-if="dialog.expressRemind" ref="expressRemindDialog" @success="handleSaveSuccess" @closed="dialog.expressRemind=false"></expressRemind>
	<expressUpdate v-if="dialog.expressUpdate" ref="expressUpdateDialog" @success="handleSaveSuccess" @closed="dialog.expressUpdate=false"></expressUpdate>
	<expressPay v-if="dialog.expressPay" ref="expressPayDialog" @success="handleSaveSuccess" @closed="dialog.expressPay=false"></expressPay>
	<expressTrace v-if="dialog.expressTrace" ref="expressTraceDialog" @closed="dialog.expressTrace=false"></expressTrace>
</template>

<script>
	// import table2excel from 'js-table2excel'
	import expressCancel from './components/expressCancel.vue'
	import expressRemind from './components/expressRemind.vue'
	import expressUpdate from './components/expressUpdate.vue'
	import expressPay from './components/expressPay.vue'
	import expressTrace from './components/expressTrace.vue'
	export default {
		name: 'orderList',
		components: {
			expressCancel,
			expressRemind,
			expressUpdate,
			expressPay,
			expressTrace
		},
		data() {
			return {
				dialog: {
					expressCancel: false,
					expressRemind: false,
					expressUpdate: false,
					expressPay: false,
					expressTrace: false
				},
				search: {
					start_time: '',
					end_time: '',
					keyword: '',
					status: '',
					code: '',
					service_provider: '',
					waybill: '',
					ordernum: '',
					member_id: ''
				},
				statuss: {
					'0': '未支付',
					'1': '已支付',
					'2': '收件中',
					'3': '待补差价',
					'4': '运输中',
					'5': '配送完成',
					'6': '系统取消',
					'7': '用户主动取消',
					'8': '取消中',
					'9': '订单关闭',
					'10': '拒收退回',
					'11': '异常',
					'12': '取消异常',
					'13': '运输异常'
				},
				codes: [],
				service_providers: [
					{ service_provider: 'yunyangwl', label: '云阳物流' },
					{ service_provider: 'kuaidi100', label: '快递100' },
					{ service_provider: 'anshunda', label: '安顺达' }
				],
				// filterData: [{
				// 	title: "状态",
				// 	key: "status",
				// 	options:
				// 	// [{
				// 	// 		label: "全部",
				// 	// 		value: "0"
				// 	// 	},
				// 	// 	{
				// 	// 		label: "未租赁",
				// 	// 		value: "1"
				// 	// 	},
				// 	// 	{
				// 	// 		label: "已租赁",
				// 	// 		value: "2"
				// 	// 	},
				// 	// 	{
				// 	// 		label: "不可租赁",
				// 	// 		value: "3"
				// 	// 	}
				// 	// ],
				// 	[
				// 		{value: '', label: '全部'},
				// 		{value: '-1', label: '删除'},
				// 		{value: '0', label: '未审核'},
				// 		{value: '1', label: '已审核'},
				// 		{value: '2', label: '已冻结'}
				// 	]
				// }, ],
				list: {
					apiObj: this.$API.order.express.list
				},
				shoplist: [],
				summaryObj: [
					{
						name: '总收入',
						value: 'totalAmount'
					},
					{
						name: '总成本',
						value: 'totalCost'
					},
					{
						name: '总利润',
						value: 'totalProfit'
					},
					{
						name: '总退款',
						value: 'refundAmount'
					}
				]
			}
		},
		computed: {
		},
		mounted() {
			// this.getInit()
			this.getCodes()
		},
		methods: {
			// 付款
			async table_pay(row){
				this.dialog.expressPay = true
				this.$nextTick(() => {
					this.$refs.expressPayDialog.open().setData(row)
				})
			},
			async getCodes() {
				// 获取快递公司列表
				var res = await this.$API.expressCompany.expressCompany.list.get({
					page: 1,
					limit: 1000,
				});
				if (res.code == 200) {
					this.codes = res.data.data
				} else {
					this.$alert(res.msg, "提示", {
						type: 'error'
					})
				}
			},
			//取消订单
			table_expressCancel(row, type){
				this.dialog.expressCancel = true
				this.$nextTick(() => {
					this.$refs.expressCancelDialog.open().setData(row, type || 0)
				})
			},
			//提醒补差价
			table_expressRemind(row){
				this.dialog.expressRemind = true
				this.$nextTick(() => {
					this.$refs.expressRemindDialog.open().setData(row)
				})
			},
			//编辑
			table_expressUpdate(row){
				this.dialog.expressUpdate = true
				this.$nextTick(() => {
					this.$refs.expressUpdateDialog.open().setData(row)
				})
			},
			//物流轨迹
			table_trace(row){
				this.dialog.expressTrace = true
				this.$nextTick(() => {
					this.$refs.expressTraceDialog.open().setData(row)
				})
			},
			async onBatchExport () {
				try {
					// 显示加载状态
					this.$message.info('正在生成导出文件，请稍候...');
					
					// 准备导出参数
					let searchParams = JSON.parse(JSON.stringify(this.search));
					
					// 如果会员ID不为空，转换为数字类型
					if (searchParams.member_id !== '') {
						searchParams.member_id = parseInt(searchParams.member_id);
					}
					
					// 如果时间戳不为空，确保是数字类型
					if (searchParams.start_time !== '') {
						searchParams.start_time = parseInt(searchParams.start_time);
					}
					if (searchParams.end_time !== '') {
						searchParams.end_time = parseInt(searchParams.end_time);
					}
					
					console.log('导出参数:', searchParams);
					
					// 调用导出API
					const res = await this.$API.order.express.list.get({
						...searchParams,
						is_export: 1
					});
					
					console.log('导出响应:', res);
					
					if (res.code == 200) {
						// 导出成功，下载文件
						this.$message.success('导出成功！');
						
						// 创建下载链接
						const link = document.createElement('a');
						link.href = res.data.file_url; // 使用正确的字段名
						link.download = res.data.file_name || '快递订单列表.xlsx';
						link.style.display = 'none';
						document.body.appendChild(link);
						link.click();
						document.body.removeChild(link);
					} else {
						this.$message.error('导出失败：' + (res.msg || '未知错误'));
					}
				} catch (error) {
					console.error('导出失败:', error);
					
					// 更详细的错误信息
					let errorMsg = '导出失败';
					if (error.response) {
						// 服务器响应了错误状态码
						errorMsg += `: ${error.response.status} - ${error.response.statusText}`;
						if (error.response.data && error.response.data.msg) {
							errorMsg += ` (${error.response.data.msg})`;
						}
					} else if (error.request) {
						// 请求已发出但没有收到响应
						errorMsg += ': 网络连接失败，请检查网络';
					} else {
						// 其他错误
						errorMsg += `: ${error.message}`;
					}
					
					this.$message.error(errorMsg);
				}
			},
			//标签切换
			tabChange(name) {
				this.search.status = name
				this.$refs.table.reload({
					...this.search
				})
			},
			//搜索
			upsearch() {
				// console.log(112, this.search)
				let search = JSON.parse(JSON.stringify(this.search))
				this.$refs.table.upData({
					...search
				})
			},
			async getInit() {
				// this.getShopList()
			},

			//删除
			async table_del(row){
				var reqData = {id: row.id}
				var res = await this.$API.order.express.delete.post(reqData);
				if(res.code == 200){
					this.$refs.table.refresh()
					this.$message.success("删除成功")
				}else{
					this.$alert(res.msg, "提示", {type: 'error'})
				}
			},
			//添加
			// add() {
			// 	this.dialog.save = true
			// 	this.$nextTick(() => {
			// 		this.$refs.saveDialog.open()
			// 	})
			// },
			//窗口编辑
			// table_edit(row) {
			// 	this.dialog.save = true
			// 	this.$nextTick(() => {
			// 		this.$refs.saveDialog.open('edit').setData(row)
			// 	})
			// },

			//本地更新数据
			handleSaveSuccess(data, mode) {
				//为了减少网络请求，直接变更表格内存数据
				console.log(data, mode)
				if (mode == 'add') {
					this.$refs.table.unshiftRow(data)
				} else if (mode == 'edit') {
					this.$refs.table.updateKey(data)
				} else {
					// 刷新表格
					this.$refs.table.refresh()
				}

				//当然也可以暴力的直接刷新表格
				// this.$refs.table.refresh()
			},
		}
	}
</script>

<style>
</style>
